package com.project.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionAttributeListener;

@Controller
@RequestMapping("scope")
public class ScopeController implements ServletRequestAttributeListener {
    //绑定共享数据
    @RequestMapping("bind")
    public String bindData(HttpServletRequest request){
        //在请求范围内共享数据
        request.setAttribute("request","request数据");
        //在用户会话范围内共享数据
        request.getSession().setAttribute("session","session数据");
        request.getSession().setAttribute("a","a数据");
        request.getSession().setAttribute("b","b数据");
        request.getSession().setAttribute("a","a***数据");
        request.getSession().removeAttribute("a");
        //在全局范围内共享数据
        request.getServletContext().setAttribute("context","context数据 ");

        return "/scope/get";
    }

    @RequestMapping("get")
    @ResponseBody
    public String getData(HttpServletRequest request){
        String str = "";
        str += "在request中绑定的共享数据："+request.getAttribute("request")+"<br>";
        str += "在HttpSession中绑定的共享数据："+request.getSession().getAttribute("session")+"<br>";
        str += "在ServletContext中绑定的共享数据："+request.getServletContext().getAttribute("context")+"<br>";

        request.getSession().invalidate();
        return str;
    }
}
